package com.godenwater.yanyu.utils;

public class StringCodeHelper {
	/**
	 * 把字节数组转换成16进制字符串
	 * @param bArray
	 * @return hexString
	 */
	public static final String bytesToHexString(byte[] bArray) {
		StringBuffer sb = new StringBuffer(bArray.length);
		String sTemp;
		for (int i = 0; i < bArray.length; i++) {
			sTemp = Integer.toHexString(0xFF & bArray[i]);
			if (sTemp.length() < 2)
				sb.append(0);
			sb.append(sTemp);
		}
		return sb.toString();
	}
	/**
	 * 把16进制字符串转换成字节数组
	 * @param hexString
	 * @return byte[]
	 */	
	  public static byte[] hexString2ByteArray(String src){
		    if(src.length() != 0){
		      String tmp;
		      int start, end;
		      int pos = src.length();
		      byte[] result = new byte[(src.length()+1)/2];

		      for(int i=0; i<result.length; i++){
		        pos   = src.length() - i*2;
		        start = ((pos-2) < 0) ? 0 : pos-2;
		        end   = src.length() - i*2;
		        result[result.length-i-1] = (byte)
		            Integer.valueOf(src.substring(start, end), 16).intValue();
		      }
		      return result;
		    }
		    return new byte[0];
		  }	
	  /**
	   * 此方法将给出的字符串按照长度在前或后补齐 0 或空格
	   * @param source
	   * @param destLength
	   * @param chrPad
	   * @param isBefore
	   * @return
	   */
	  public static String fillupString(String source,int destLength,char chrPad,boolean isBefore)
	  {
	    StringBuffer padString=new StringBuffer();
	    if(source.length()>=destLength) return source;
	    for(int i=0;i<(destLength-source.length());i++)
	    {
	      padString.append(chrPad);
	    }
	    if(isBefore==true)
	    {
	      return padString.toString() + source;
	    }else
	    {
	      return  source +padString.toString() ;
	    }
	  }

	  /**
	   * 字节转换为二进制(8bit)
	   * @param var
	   * @return
	   */
	  public static String byte2BinaryString(byte var) {
	    String result = "";
	    result = Integer.toBinaryString(var);
	    result= fillupString(result,32,'0',true);

	    return result.substring(24);//取最后8bit
	  }
	  public static void main(String[] args){
		  byte[] b = hexString2ByteArray("19");
		  String c = byte2BinaryString(b[0]);
		  System.out.println(c);
		  
		  int d = Integer.valueOf(c.substring(0, 5), 2).intValue();
		  System.out.println(d);
	  }
}
